#!/usr/bin/env python
# Create: 2018/10/15
__author__ = '749B'

import os
import pickle
import requests


class MySession(requests.Session):

    def __init__(self, file=None):
        super(MySession, self).__init__()
        # 替换成Windows的Edge的User-Agent
        self.headers['User-Agent'] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " \
                                     "AppleWebKit/537.36 (KHTML, like Gecko) " \
                                     "Chrome/64.0.3282.140 Safari/537.36 Edge/17.17134"
        self.file = file if file else __file__
        self.base_dir = os.path.dirname(os.path.abspath(self.file)) if file else\
            os.path.dirname(os.path.dirname(os.path.abspath(self.file)))
        self.pk_name = "%s/pk/session.pk" % self.base_dir

    def save(self, bak_path=None):
        """序列化保存session"""
        print("序列化session保存：%s" % self.pk_name)
        with open(self.pk_name, 'wb') as f:
            pickle.dump(self, f)

    def load(self):
        """反序列化读取session"""
        if os.path.exists(self.pk_name):
            print("反序列化session加载：%s" % self.pk_name)
            with open(self.pk_name, 'rb') as f:
                return pickle.load(f)
        print("加载session文件不存在：%s" % self.pk_name)


if __name__ == '__main__':
    s = MySession()
    # print(hasattr(s, 'path'))  # 检查原生对象里是否已经有某个属性了
    print(s.file)

